package cn.northsea.service.impl;

import cn.northsea.mapper.WarehouseMapper;
import cn.northsea.pojo.*;
import cn.northsea.service.WarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;

@Service
public class WarehouseServiceImpl implements WarehouseService {
    @Autowired
    private WarehouseMapper warehouseMapper;

    @Override
    public List<WarehouseProductVo> findWarehouseProductAll(String likename) {
        return warehouseMapper.findWarehouseProductAll(likename);
    }

    @Override
    public List<WarehouseOutVo> WarehouseOutList(String likename, String start, String end) {
        return warehouseMapper.WarehouseOutList(likename, start, end);
    }

    @Override
    public List<WarehouseInVo> WarehouseInList(String likename, String start, String end) {
        return warehouseMapper.WarehouseInList(likename, start, end);
    }

    @Override
    public List<WarehouseMaterialVo> findWarehouseMaterialAll(String likename) {
        return warehouseMapper.findWarehouseMaterialAll(likename);
    }

    @Override
    public String checkMaterialQuantity(Integer materialId, Double materialQuantity) {
        List<WarehouseMaterial> warehouseMaterialList = warehouseMapper.findWarehouseMaterialByMid(materialId);
        if (warehouseMaterialList != null) {
            for (WarehouseMaterial warehouseMaterial : warehouseMaterialList) {
                if (warehouseMaterial.getWarehouseMaterialQuantity() >= materialQuantity) {
                    return "OK";
                }
            }
        }
        return "ERROR";
    }

    @Override
    @Transactional
    public void updateWarehouseMaterial(Double materialQuantity, Integer materialId, Integer getMaterialId) {
        List<WarehouseMaterial> warehouseMaterialList = warehouseMapper.findWarehouseMaterialByMid(materialId);
        if (warehouseMaterialList != null) {
            for (WarehouseMaterial warehouseMaterial : warehouseMaterialList) {
                if (warehouseMaterial.getWarehouseMaterialQuantity() >= materialQuantity) {
                    warehouseMapper.updateWarehouseMaterial(warehouseMaterial.getWarehouseMaterialId(), materialQuantity);
                    warehouseMapper.addWarehouseOut(materialQuantity, warehouseMaterial.getMaterialId(), new Date(System.currentTimeMillis()), warehouseMaterial.getWarehouseId());
                    warehouseMapper.updateGetMaterialStatus(getMaterialId);
                    break;
                }
            }
        }
    }
}
